﻿@{
    Layout = "~/Views/Shared/_LayoutAdminPage.cshtml";
}

@section header{

    <style>
        #articleThumbTable + .layui-table-view .layui-table-body tbody > tr > td {
            padding: 0;
        }

            #articleThumbTable + .layui-table-view .layui-table-body tbody > tr > td > .layui-table-cell {
                height: 48px;
                line-height: 48px;
            }

        .tb-img-circle {
            width: 90px;
            height: 40px;
            cursor: zoom-in;
            /* border-radius: 50%;
            border: 2px solid #dddddd;*/
        }


        .articleThumb-info-img {
            width: 42%;
            height: 110px;
            line-height: 110px;
            /* position: relative; */
            /* display: inline-block; */
            /* border: 2px solid #eee; */
            /*border-radius: 50%;*/
            overflow: hidden;
            cursor: pointer;
            margin: 0 auto;
        }

            .articleThumb-info-img:hover:after {
                content: '\e681';
                position: absolute;
                text-align: center;
                top: 0;
                left: 0px;
                right: 0;
                bottom: 0;
                color: #fff;
                background-color: rgba(0, 0, 0, 0.3);
                font-size: 28px;
                padding-top: 2px;
                font-style: normal;
                font-family: layui-icon;
                -webkit-font-smoothing: antialiased;
                -moz-osx-font-smoothing: grayscale;
            }

            .articleThumb-info-img img {
                width: 100%;
                height: 110px;
            }
    </style>

}

<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 表格工具栏 -->
            <form class="layui-form toolbar">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">类&emsp;别:</label>
                        <div class="layui-input-inline">
                            <select name="cateId">
                                <option value="-1">所有</option>
                                @foreach (var item in Model)
                                {
                                    <option value="@item.id">@item.name</option>
                                }
                            </select>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">标&emsp;题:</label>
                        <div class="layui-input-inline">
                            <input name="title" class="layui-input" placeholder="输入标题" />
                        </div>
                    </div>

                    <div class="layui-inline">
                        <label class="layui-form-label">状&emsp;态:</label>
                        <div class="layui-input-inline">
                            <select name="status">
                                <option value="-1">所有</option>
                                <option value="1">正常</option>
                                <option value="0">冻结</option>
                            </select>
                        </div>
                    </div>

                    <div class="layui-inline form-search-show-expand">
                        <label class="layui-form-label">是否置顶:</label>
                        <div class="layui-input-inline">
                            <select name="ontop">
                                <option value="-1">所有</option>
                                <option value="1">是</option>
                                <option value="0">否</option>
                            </select>
                        </div>
                    </div>

                    <div class="layui-inline form-search-show-expand">
                        <label class="layui-form-label">是否推荐:</label>
                        <div class="layui-input-inline">
                            <select name="iselite">
                                <option value="-1">所有</option>
                                <option value="1">是</option>
                                <option value="0">否</option>
                            </select>
                        </div>
                    </div>

                    <div class="layui-inline  form-search-show-expand">
                        <label class="layui-form-label">发布日期:</label>
                        <div class="layui-input-inline">
                            <input name="releaseDate" class="layui-input icon-date" placeholder="选择日期范围" autocomplete="off" />
                        </div>
                    </div>

                    <div class="layui-inline">
                        &emsp;
                        <button class="layui-btn icon-btn" lay-filter="articleTbSearch" lay-submit>
                            <i class="layui-icon">&#xe615;</i>搜索
                        </button>
                        <a class="layui-btn form-search-expand" search-expand>
                            展开 <i class="layui-icon layui-icon-down"></i>
                        </a>
                    </div>
                </div>
            </form>
            <!-- 数据表格 -->
            <table id="articleTable" lay-filter="articleTable"></table>
        </div>
    </div>
</div>


<!-- 表格操作列 -->
<script type="text/html" id="articleTbBar">
    <a class="layui-btn layui-btn-xs" lay-event="visit">访问</a>
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>


<!-- 表单弹窗 -->
<script type="text/html" id="articleEditDialog">
    <form id="articleCateEditForm" lay-filter="articleEditForm" class="layui-form model-form">
        <div class="layui-row">
            <div class="layui-col-md6">
                <input name="id" value="0" type="hidden" />
                <div class="layui-form-item">
                    <label class="layui-form-label layui-form-required">类&emsp;别:</label>
                    <div class="layui-input-block">
                        <select name="cateId">
                            @foreach (var item in Model)
                            {
                                <option value="@item.id">@item.name</option>
                            }
                        </select>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label layui-form-required">标&emsp;题:</label>
                    <div class="layui-input-block">
                        <input name="title" placeholder="请输入标题" class="layui-input"
                               lay-verType="tips" lay-verify="required" required />
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">副标题:</label>
                    <div class="layui-input-block">
                        <input name="subhead" placeholder="请输入副标题" class="layui-input" value="" />
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">简&emsp;介:</label>
                    <div class="layui-input-block">
                        <input name="intro" placeholder="请输入简介" class="layui-input" value="" />
                    </div>
                </div>


                <div class="layui-form-item">
                    <label class="layui-form-label">SEO关键词:</label>
                    <div class="layui-input-block">
                        <input name="keywords" placeholder="请输入SEO关键词" value="" class="layui-input" />
                        <div class="layui-word-aux">不填写则按SEO默认方案配置</div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">SEO描述:</label>
                    <div class="layui-input-block">
                        <input name="description" placeholder="请输入SEO描述" value="" class="layui-input" />
                        <div class="layui-word-aux">不填写则按SEO默认方案配置</div>
                    </div>
                </div>


                <div class="layui-form-item">
                    <label class="layui-form-label layui-form-required">作者ID:</label>
                    <div class="layui-input-block">
                        <input name="author" placeholder="请输入作者ID" class="layui-input inline-block" value="" lay-verType="tips" lay-verify="required|number" style="width: 130px;" required />
                        <button type="button" class="layui-btn layui-btn-primary selectAuthorBtn" typeid="1">选择</button>
                    </div>
                </div>


                <div class="layui-form-item">
                    <label class="layui-form-label">来&emsp;源:</label>
                    <div class="layui-input-block">
                        <input name="copyfrom" placeholder="请输入来源" class="layui-input" value="" />
                    </div>
                </div>


            </div>

            <div class="layui-col-md6">
                <div class="layui-form-item" id="editArticleThumbImage">
                    <label class="layui-form-label">缩略图:</label>
                    <div class="layui-input-block">
                        <div class="articleThumb-info-img" id="articleThumbInfoImg">
                            <img src="" alt="" />
                            <input name="thumb" type="hidden" value="" class="layui-input" />
                        </div>
                    </div>
                </div>

                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <input placeholder=" 宽度" class="layui-input inline-block widthThumb" value="300" type="number" style="width: 60px;" />

                        <button type="button" class="layui-btn layui-btn-primary GetArticleThumbBtn">获取文章缩略图</button>
                    </div>
                </div>


                <div class="layui-form-item">
                    <label class="layui-form-label layui-form-required">排序:</label>
                    <div class="layui-input-block">
                        <input name="sort" placeholder="请输入排序号" value="1" type="number" class="layui-input"
                               lay-verType="tips" lay-verify="required|number" required />
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label layui-form-required">点击数:</label>
                    <div class="layui-input-block">
                        <input name="hits" placeholder="请输入点击数" value="0" type="number" class="layui-input"
                               lay-verType="tips" lay-verify="required|number" required />
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">是否置顶:</label>
                    <div class="layui-input-block">
                        <input type="radio" name="ontop" value="1" title="是" />
                        <input type="radio" name="ontop" value="0" title="否" checked />
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">是否推荐:</label>
                    <div class="layui-input-block">
                        <input type="radio" name="iselite" value="1" title="是" />
                        <input type="radio" name="iselite" value="0" title="否" checked />
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label layui-form-required">状态:</label>
                    <div class="layui-input-block">
                        <input type="radio" name="status" value="1" title="正常" checked />
                        <input type="radio" name="status" value="0" title="冻结" />
                    </div>
                </div>
            </div>
        </div>


        <div class="layui-form-item layui-form-text">
            <label class="layui-form-label">文章内容:</label>
            <div class="layui-input-block">
                <textarea id="htmlContentTool" name="content"></textarea>
            </div>
        </div>


        <div class="layui-form-item text-right">
            <button class="layui-btn" lay-filter="articleEditSubmit" lay-submit>保存</button>
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
        </div>
    </form>
</script>

<script type="text/html" id="selectAuthorDialog">
    <form id="eCourseEditForm" lay-filter="eCourseEditForm" class="layui-form model-form">
        <div class="layui-form-item">
            <label class="layui-form-label">账&emsp;号：</label>
            <div class="layui-inline">
                <input name="username" placeholder="输入账号" type="text" class="layui-input" maxlength="20" />
            </div>
            <div class="layui-inline">
                &emsp;
                <button class="layui-btn icon-btn" lay-filter="userTbSearch" lay-submit>
                    <i class="layui-icon">&#xe615;</i>搜索
                </button>
            </div>
        </div>
        <div class="layui-form-item" style="position: relative;">
            <label class="layui-form-label">选择用户：</label>
            <div class="layui-input-block">
                <table id="userTable" lay-filter="userTable"></table>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            <button class="layui-btn" lay-filter="selectAuthorSubmit" lay-submit>确定</button>
        </div>
    </form>
</script>



<script type="text/javascript" src="/assets/libs/tinymce/tinymce.min.js"></script>
<script>
    layui.use(['layer', 'form', 'table', 'util', 'admin', 'xmSelect', 'notice', 'fileChoose', 'laydate'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var util = layui.util;
        var admin = layui.admin;
        var xmSelect = layui.xmSelect;
        var notice = layui.notice;
        var fileChoose = layui.fileChoose;
        var laydate = layui.laydate;



        /* 渲染表格 */
        var insTb = table.render({
            elem: '#articleTable',
            url: '/api/admin/Article/GetArticleList',
            //limit: 20, //默认展示数
            page: true,
            toolbar: ['<p>',
                '<button lay-event="add" class="layui-btn layui-btn-sm icon-btn"><i class="layui-icon">&#xe654;</i>添加</button>&nbsp;',
                '<button lay-event="del" class="layui-btn layui-btn-sm layui-btn-danger icon-btn"><i class="layui-icon">&#xe640;</i>删除</button>',
                '</p>'].join(''),
            cellMinWidth: 100,
            cols: [[
                { type: 'checkbox' },
                { field: 'id', width: 60, align: 'center', sort: true },
                { field: 'title', title: '标题', align: 'center' },
                { field: 'nickname', title: '作者', align: 'center' },
                { field: 'cateName', title: '类别', align: 'center' },
                { field: 'hits', title: '点击量', align: 'center' },
                { field: 'sort', title: '排序', sort: true },
                {
                    field: 'status', title: '状态', templet: function (d) {
                        var strs = [
                            '<span class="text-danger">冻结</span>',
                            '<span class="text-success">正常</span>'
                        ];
                        return strs[d.status];
                    }, align: 'center', sort: true
                },
                {
                    field: 'createTime', title: '创建时间', templet: function (d) {
                        return util.toDateString(d.createTime);
                    }, sort: true
                },
                { title: '操作', toolbar: '#articleTbBar', align: 'center', minWidth: 200 }
            ]]
        });

        //日期范围
        laydate.render({
            elem: 'input[name="releaseDate"]',
            type: 'date',
            range: true,
            trigger: 'click'
        });

        /* 表格搜索 */
        form.on('submit(articleTbSearch)', function (data) {
            data.field
            insTb.reload({ where: data.field, page: { curr: 1 } });
            return false;
        });

        /* 表格工具条点击事件 */
        table.on('tool(articleTable)', function (obj) {
            if (obj.event === 'edit') { // 修改
                showEditModel(obj.data);
            } else if (obj.event === 'del') { // 删除
                doDel(obj);
            } else if (obj.event === 'visit') {
                window.open("/Detail/" + obj.data.id + ".html");
            }
        });

        /* 表格头工具栏点击事件 */
        table.on('toolbar(articleTable)', function (obj) {
            if (obj.event === 'add') { // 添加
                showEditModel();
            } else if (obj.event === 'del') { // 删除
                var checkRows = table.checkStatus('articleTable');
                if (checkRows.data.length === 0) {
                    layer.msg('请选择要删除的数据', { icon: 2 });
                    return;
                }
                var ids = checkRows.data.map(function (d) {
                    return d.id;
                });
                doDel({ ids: ids });
            }
        });

        /* 显示表单弹窗 */
        function showEditModel(mData) {
            admin.open({
                type: 1,
                area: '1080px',
                maxmin: true,
                resize: true,
                title: (mData ? '修改' : '添加') + '文章',
                content: $('#articleEditDialog').html(),
                success: function (layero, dIndex) {
                    //解决编辑框层级问题
                    $(".layui-layer-admin[contype='string']").css("z-index", 1000);
                    $(".layui-layer-shade").css("z-index", 1);

                    // 回显表单数据
                    form.val('articleEditForm', mData);

                    if (mData) {
                        $("#articleThumbInfoImg >img").attr("src", mData.thumb);
                    }

                    /* 选择图片 */
                    $('#articleThumbInfoImg').click(function () {
                        fileChoose.open({
                            fileUrl: '',
                            listUrl: '/api/admin/File/getfile',
                            num: 3,
                            dialog: {
                                offset: '60px'
                            },
                            upload: {
                                data: {
                                    dir: function () {
                                        return $('#tv-current-position').text();
                                    }
                                },
                                url: "/api/admin/Public/Upload/UploadFile2"
                            },
                            onChoose: function (urls) {
                                $('#articleThumbInfoImg > img').attr('src', urls[0].url);
                                $('#articleThumbInfoImg > input').val(urls[0].url);
                                //layer.msg('你选择了：' + JSON.stringify(urls), { icon: 1 });
                            }
                        });


                    });

                    $(".selectAuthorBtn").click(function () {
                        admin.open({
                            type: 1,
                            title: '选择作者',
                            content: $('#selectAuthorDialog').html(),
                            area: ['640px', '700px'],
                            success: function (layero, userdIndex) {
                                var goodinsTb = table.render({
                                    elem: '#userTable',
                                    url: '/api/admin/Account/GetAdminList',
                                    page: true,
                                    cellMinWidth: 100,
                                    cols: [[
                                        { type: 'checkbox' },
                                        { field: 'id', width: 60 },
                                        { field: 'username', title: '账号', align: 'center', sort: true },
                                        { field: 'nickname', title: '昵称' },
                                        {
                                            field: 'status', title: '状态', templet: function (d) {
                                                var strs = [
                                                    '<span class="text-danger">冻结</span>',
                                                    '<span class="text-success">正常</span>'
                                                ];
                                                return strs[d.status];
                                            }, align: 'center', sort: true
                                        }
                                    ]]
                                });

                                form.on('submit(userTbSearch)', function (data) {
                                    goodinsTb.reload({ where: data.field, page: { curr: 1 } });
                                    return false;
                                });
                                form.on('submit(selectAuthorSubmit)', function (data) {
                                    var checkRows = table.checkStatus('userTable');
                                    if (checkRows.data.length != 1) {
                                        layer.msg('请选择一条数据', { icon: 2 });
                                    } else {
                                        var udata = checkRows.data;
                                        $('input[name="author"]').val(udata[0].id);
                                        layer.close(userdIndex);
                                        notice.msg('您已选择了作者', { icon: 5 });
                                    }
                                    return false;
                                });
                            }
                        });

                    });

                    // 渲染代码富文本编辑器
                    tinymce.init({
                        selector: '#htmlContentTool',
                        height: 500,
                        branding: false,
                        language: 'zh_CN',
                        plugins: 'code image axupimgs print preview fullscreen paste searchreplace save autosave link autolink image imagetools media table codesample lists advlist hr charmap emoticons anchor directionality pagebreak quickbars nonbreaking visualblocks visualchars wordcount',
                        toolbar: 'code axupimgs | fullscreen preview code | undo redo | forecolor backcolor | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | outdent indent | numlist bullist | formatselect fontselect fontsizeselect | link image media emoticons charmap anchor pagebreak codesample | ltr rtl',
                        toolbar_drawer: 'sliding',
                        images_upload_url: '/api/admin/Public/Upload/UploadFile2?resultType=tinymce',
                        file_picker_types: 'media',
                        file_picker_callback: function (callback, value, meta) {
                            fileChoose.open({
                                fileUrl: '',
                                listUrl: '/api/admin/File/getfile',
                                num: 3,
                                dialog: {
                                    offset: '60px'
                                },
                                upload: {
                                    data: {
                                        dir: function () {
                                            return $('#tv-current-position').text();
                                        }
                                    },
                                    url: "/api/admin/Public/Upload/UploadFile2",
                                     exts:"jpg|jpeg|gif|mp4|mp3|png|webp|avi|doc|docx|txt|doc|xls|m4v|wmv"
                                },
                                onChoose: function (urls) {
                                    callback(urls[0].url);
                                }
                            });
                            setTimeout(function () {
                                $(".layer-file-choose").css("z-index", "300000000");
                            }, 200)
                        },
                        images_upload_handler: function (blobInfo, succFun, failFun) {
                            var xhr, formData;
                            var file = blobInfo.blob();//转化为易于理解的file对象
                            xhr = new XMLHttpRequest();
                            xhr.withCredentials = false;
                            xhr.open('POST', '/api/admin/Public/Upload/UploadFile2?resultType=tinymce');
                            xhr.onload = function() {
                                var json;
                                if (xhr.status != 200) {
                                    failFun('HTTP Error: ' + xhr.status);
                                    return;
                                }
                                json = JSON.parse(xhr.responseText);
                                if (!json || typeof json.location != 'string') {
                                    failFun('Invalid JSON: ' + xhr.responseText);
                                    return;
                                }
                                succFun(json.location);
                            };
                            formData = new FormData();
                            formData.append('file', file, file.name );
                            xhr.send(formData);
                        },
                        init_instance_callback: function (editor) {
                            //console.log("init_instance_callback");
                            if (mData) {
                                $.post("/api/Admin/Article/GetArticleContent", { id: mData.id }, function (res2) {
                                    tinymce.get('htmlContentTool').setContent(res2.data);
                                }, 'json');
                            }
                        }
                    });

                    //获取文章缩略图
                    var thumbIn = 0;
                    $(".GetArticleThumbBtn").click(function () {
                        var htmlContent = tinymce.get('htmlContentTool').getContent();
                        var arr = getimgsrc(htmlContent);
                        if (arr.length == 0) {
                            return;
                        }
                        if ((thumbIn + 1) > arr.length) {
                            thumbIn = 0;
                        }
                        if (arr[thumbIn].indexOf("/upload/") == 0 || arr[thumbIn].indexOf("../upload/") == 0) {
                            arr[thumbIn] = arr[thumbIn].replace("../", "/").replace("/upload", "/");
                            var widthThumb = $(".widthThumb").val();
                            var thumbUrl = "/Images/GetPath?name=" + arr[thumbIn];
                            if (widthThumb != "") {
                                thumbUrl += ("&width=" + widthThumb);
                            }
                            //widthThumb
                            $('#articleThumbInfoImg > img').attr('src', thumbUrl);
                            $('#articleThumbInfoImg > input').val(thumbUrl);
                        } else {
                            $('#articleThumbInfoImg > img').attr('src', arr[thumbIn]);
                            $('#articleThumbInfoImg > input').val(arr[thumbIn]);
                        }

                        thumbIn++;
                    })

                    // 表单提交事件
                    form.on('submit(articleEditSubmit)', function (data) {
                        var loadIndex = layer.load(2);
                        var htmlContent = tinymce.get('htmlContentTool').getContent();
                        data.field.content = htmlContent ? htmlContent : "";
                        $.post(mData ? '/api/admin/Article/EditArticleInfo' : '/api/admin/Article/AddArticleInfo', data.field, function (res2) {
                            layer.close(loadIndex);
                            if (1 == res2.code) {
                                layer.close(dIndex);
                                layer.msg(res2.message, { icon: 1 });
                                insTb.reload({ page: { curr: 1 } });
                            } else {
                                layer.msg(res2.message, { icon: 2 });
                            }
                        }, 'json');
                        return false;
                    });
                },
                end: function () {
                    tinymce.get('htmlContentTool').destroy(false);
                }
            });
        }

        /* 删除 */
        function doDel(obj) {
            layer.confirm('确定要删除选中数据吗！？', {
                skin: 'layui-layer-admin',
                shade: .1
            }, function (i) {
                layer.close(i);
                var loadIndex = layer.load(2);
                $.post('/api/admin/Article/DeleteArticle', {
                    ids: obj.data ? obj.data.id : obj.ids.join(',')
                }, function (res) {
                    layer.close(loadIndex);
                    if (res.code == 1) {
                        layer.msg(res.message, { icon: 1 });
                        insTb.reload({ page: { curr: 1 } });
                    } else {
                        layer.msg(res.message, { icon: 2 });
                    }
                }, 'json');
            });
        }

        function getimgsrc(htmlstr) {
            var reg = /<img.+?src=('|")?([^'"]+)('|")?(?:\s+|>)/gim;
            var arr = [];
            while (tem = reg.exec(htmlstr)) {
                arr.push(tem[2]);
            }
            return arr;
        }

    });

</script>

